// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'cloud1-3gypuez7864a550c'
})
const db = cloud.database();
const _ = db.command;
// 云函数入口函数
exports.main = async (event, context) => {
  const openid = cloud.getWXContext().OPENID;
  let inc=1
  let {
    wkid,
    nickName,
    avatarUrl
  } = event;
  let res1 = await db.collection("demo_vote_users").where({
    openid
  }).get();
  //此人存在时
  if (res1.data.length) {
    //取消点赞
    let res2 =await db.collection("demo_vote_users").where({
      openid,
      wkid: _.all([wkid])
    }).count();
    if (res2.total) {
      //取消点赞时已存在该图片，删除
      await db.collection("demo_vote_users").where({
        openid
      }).update({
        data: {
          wkid: _.pull(wkid)
        }
      });
      inc=-1;
    } else {
      //点赞未存在再追加
      await db.collection("demo_vote_users").where({
        openid
      }).update({
        data: {
          wkid: _.addToSet(wkid)
        }
      });
    }
  } else {
    //此人不存在时添加人
    await db.collection("demo_vote_users").add({
      data: {
        openid,
        wkid: [wkid],
        nickName,
        avatarUrl
      }
    })
  }
  return await db.collection("demo_vote_works").doc(wkid).update({
    data: {
      count: _.inc(inc)
    }
  })
}